<?php
/**
 * @author spenceryg
 * @date 2023/3/28
 * @time 8:58 下午
 * @focus love & life
 */


namespace app\api\controller;

use app\admin\validate\UploadValidate;
use app\common\model\ImgClass;
use app\common\model\MemberFile;
use app\common\model\MemberPointsLog;
use hg\apidoc\annotation as Apidoc;
use OSS\OssClient;
use think\exception\ValidateException;

/**
 * Class FileManager
 * @package app\api\controller
 *
 * @Apidoc\Title("图片管理")
 * @Apidoc\Group("api")
 */
class FileManager extends Auth
{
    const UPLOAD_DOMAIN="https://oss.ai-dog.net";
    const UPLOAD_URL="https://oss.ai-dog.net/index.php";
    const UPLOAD_KEY="jNf@1lF4x4Z206bL7PdDy5tE8mQaUzIcOgWsApVqYhR3X9wS4o1NkBnJtGvC";//上传接口秘钥

    /**
     * upload
     * @Apidoc\Title("图片上传")
     */
    public function upload()
    {
        $class_id = input('class_id');
        if(!$class_id) {
            $class_id = ImgClass::where('member_id', $this->request->uid)->order('sort', 'asc')->value('id');
        }
        $config = [];
        $config['pubid'] = make_pubid();
        $config['listtype'] = input("get.listtype");
        $file = request()->file();

        try{
            $rules = [
                'file' => [
                    'fileExt' =>  config('memberfile.file_extension'),
                    'fileSize' =>   config('memberfile.file_size') * 1024
                ]
            ];
            validate($rules)->check($file);
        }catch (ValidateException $e) {
            return error($e->getMessage(),'', '', 500);
        }


        // 积分验证
        $member_id = $this->request->uid;
        $member = \app\common\model\Member::find($member_id);
        $cost_points =  config('user.point_per_img');
        $member_point_num = $member['point_num'];
        if ($member_point_num > $cost_points) {
            \app\common\model\Member::update([
                'id' => $member_id,
                'point_num' => $member_point_num - $cost_points
            ]);
            $point_log = MemberPointsLog::create([
                'member_id' => $member_id,
                'num' => -1 * $cost_points,
                'end_num' => $member_point_num - $cost_points,
                'remarks' => "图片上传"
            ]);
        } else {
            return error('积分不足, 请充值积分！', 'recharge', '', 500);
        }

        $file = $file['file'];
        //查询文件是否存在
        $hasdata=MemberFile::where([
            ["member_id",'=',$this->request->uid],
            ["md5",'=',$file->hash('md5')],
        ])->find();  
        if($hasdata){
            return success('上传成功(此图片已存在)', ['url'=>$hasdata['filepath']]);
        }  
        
        
        $savepath = \think\facade\Filesystem::disk('public')->putFile('memberUploadCache', $file,'uniqid');
        $filepath = str_replace("\\", "/", $savepath);
        $filepath = "/storage/" . $filepath;
        $data = [];
        $data['pubid'] = $config['pubid'];
        $data['savepath'] = $savepath;
        $data["filepath"] = $filepath;
        $data["name"] = $file->getOriginalName();
        $data["ext"] = $file->getOriginalExtension();
        $data["mime"] = $file->getOriginalMime();
        $data["md5"] = $file->hash('md5');
        $data["sha1"] = $file->hash('sha1');
        $data["size"] = $file->getSize();
        $data['member_id'] = $this->request->uid;
        //接口URL
        $uploadUrl = self::UPLOAD_URL;
        // 文件保存的相对路径（可根据实际情况替换）
        $savePath = date("Y")."/".date("m")."/".date("d");
        // 构建POST请求的数据
        $postData = [
            'file'=>new \CURLFile(".".$filepath),
            'action'=>'upload',
            'savepath' => $savePath,
            'key' => self::UPLOAD_KEY
        ];
        // 初始化cURL会话
        $ch = curl_init();
        // 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, $uploadUrl);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 忽略SSL证书验证（不建议在生产环境中使用）
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // 执行cURL请求并获取结果
        $response = curl_exec($ch);
        // 关闭cURL会话
        curl_close($ch);
        // 处理接口返回结果
        $result = json_decode($response,true);
        // 输出结果
        if($result['status']){
            $data['filepath'] = self::UPLOAD_DOMAIN.$result['url'];
            $data['savepath'] = $result['url'];
            //删除本站点上的附件
            unlink(".".$filepath);
            $data['img_class_id'] = $class_id;
            $apiFile = MemberFile::create($data);
            return success('上传成功', ['url'=>$data['filepath']]);
        }else{
            return error('上传失败'.$result['msg']);exit;
        }
    }


    /**
     * list
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @Apidoc\Title("获取图片列表")
     */
    public function list()
    {
        $list_rows = input('list_rows', 10, 'intval');
        $where = [];
        $keywords = input('keywords','', 'trim');
        if($keywords) {
            $where[] = ['name', 'like', '%'. $keywords .'%'];
        }

        $class_id = input('class_id', 0, 'intval');
        if($class_id) {
            $where[] = ['img_class_id', '=', $class_id];
        }
        $where[] = ['member_id', '=', $this->request->uid];

        $res = MemberFile::with('imgClass')->where($where)
            ->order('id', 'desc')
            ->paginate($list_rows);
        return success('ok',$res);
    }


    /**
     * delete
     * @Apidoc\Title("删除图片")
     * @Apidoc\Param("id")
     */
    public function delete()
    {
        $id = input('id');
        if(is_array($id)){
            foreach($id as $id2){
                $file = MemberFile::find($id2);
                if($file['member_id'] != $this->request->uid) {
                    return error('非法请求');
                }else{
                    $this->deleteSub($file);
                }      
            }
        }else{
            $file = MemberFile::find($id);
            if($file['member_id'] != $this->request->uid) {
                return error('非法请求');
            }else{
                $result=$this->deleteSub($file);
            } 
        }
        return success('删除成功');
    }
    //删除循环调用
    private function deleteSub($file){
        //如果filepath包含阿里云链接，则删除
        if(strstr($file['filepath'],'aliyuncs.com',)){
            $ossClient = new OssClient('LTAIaXEq17byR1mJ', 'miM4lVW6iu2To6PPnOFVSyOvBpPlE8', 'oss-cn-shanghai.aliyuncs.com');
            $ossClient->deleteObject('ai-dogimg',basename($file['filepath'])); 
        }
        // 构建POST请求的数据
        $postData = [
            'action'=>'delete',
            'filepath' => $file['savepath'],
            'key' => self::UPLOAD_KEY
        ];
        //接口URL
        $uploadUrl = self::UPLOAD_URL;        
        // 初始化cURL会话
        $ch = curl_init();
        // 设置cURL选项
        curl_setopt($ch, CURLOPT_URL, self::UPLOAD_URL);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        // 忽略SSL证书验证（不建议在生产环境中使用）
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        // 执行cURL请求并获取结果
        $response = curl_exec($ch);
        // 关闭cURL会话
        curl_close($ch);
        // 处理接口返回结果
        $result = json_decode($response,true);
        //删除数据库里的信息
        MemberFile::destroy($file['id']);
    }

    /**
     * changeClass
     * @Apidoc\Title("转移图片分类")
     * @Apidoc\Method("post")
     * @Apidoc\Param("ids",type="array",require=true,desc="id数组")
     * @Apidoc\Param("article_class_id",type="int",require=true,desc="目标分类id")
     */
    public function changeClass(): \think\response\Json
    {
        $data = request()->post(['ids', 'img_class_id']);
        validate([
            'ids|图片id' => 'require',
            'img_class_id|目标分类' => 'require',
        ])->check($data);
        foreach ($data['ids'] as $id) {
            $member_id = MemberFile::where('id', $id)->value('member_id');
            if($member_id != $this->request->uid) {
                return error('非法请求！');
            }
        }
        MemberFile::where('id', 'in', $data['ids'])->save([
            'img_class_id' => $data['img_class_id']
        ]);
        return success("操作成功");
    }
    /**
     * getConfig
     * @Apidoc\Title("获取上传配置")
     */
    public function getConfig(): \think\response\Json
    {
        return success('', [
            'fileExt' =>  config('memberfile.file_extension'),
            'fileSize' =>   config('memberfile.file_size')
        ]);
    }
}
